import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by hasee on 2018/1/29.
 */
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("do get ..........");
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println(">>>>>>>>>>>post---------------");
        String userName = req.getParameter("username");
        String passwd = req.getParameter("password");

        Subject curUser = SecurityUtils.getSubject();
        UsernamePasswordToken tocken = new UsernamePasswordToken(userName,passwd);

        try {
            curUser.login(tocken);

            Session session = curUser.getSession();
            System.out.println(session.getId());
            System.out.println(session.getTimeout());
            System.out.println(session.getHost());

            session.setAttribute("keyName","sessionValue");

            resp.sendRedirect("success.jsp");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            req.setAttribute("loginErr","account or passwd is error !!");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
